<template>
  <el-card>
    <base-table
        ref="tableRef"
        v-loading="loading"
        :data="tableData"
        :fields="tableFields"
        :total="total"
        @add="handleAdd"
        @delete="handleDelete"
        @edit="handleEdit"
        @query="handleQuery"
        @batch-delete="handleBatchDelete"
    >
      <!-- 自定义搜索字段 -->
      <template #search-fields="{ searchForm }">
      </template>

      <template #price="{row}">
        <span class="price"> ￥{{ row.price }}</span>
      </template>
      <template #merchantId="{row}">
        {{ row.merchantName }}
      </template>
      <template #categoryId="{row}">
        <el-tag>{{ row.categoryName }}</el-tag>
      </template>

      <!-- 自定义操作列 -->
      <template #operations="{ row }">
        <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
        <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
      </template>
    </base-table>

    <!-- 表单对话框 -->
    <base-dialog
        ref="dialogRef"
        :fields="formFields"
        :title="dialogTitle"
        @submit="handleSubmit"
    />
  </el-card>
</template>

<script setup>
import {computed, onMounted, ref} from 'vue'
import {ElMessage} from 'element-plus'
import {confirm} from '@/utils/utils.js'
import request from '@/utils/request'
import BaseTable from "@/components/common/BaseTable.vue";
import BaseDialog from "@/components/common/BaseDialog.vue";
import {fields} from '@/model/Dish.js'
import {useStore} from "vuex";

const store = useStore()
const tableFields = fields.filter(e => {
  return !(store.state.userInfo.role !== 'admin' && ['merchantId'].includes(e.prop));
})

// 初始化
onMounted(async () => {
  await handleQuery()
  const remoteFields = fields.filter(field => field.type === 'remote-select' && field.search)
  for (let field of remoteFields) {
    field.options = await field.api()
  }
})

// 查询相关
const total = ref(0)
const tableData = ref([])
const tableRef = ref(null)
const loading = ref(false)
const handleQuery = async () => {
  try {
    loading.value = true
    const res = await request.post('/dish/page', tableRef.value?.getQueryParam() || {})
    tableData.value = res.records
    total.value = res.total
  } finally {
    loading.value = false
  }
}

// 表单相关
const dialogRef = ref(null)
const dialogTitle = ref(null)
let formFields = computed(() => {
  return fields
})

const handleAdd = () => {
  dialogTitle.value = '新增菜品'
  dialogRef.value.open({
    isHot: true,
    isNew: true,
  })
}

const handleEdit = (row) => {
  dialogTitle.value = '修改菜品'
  dialogRef.value.open(row)
}

const handleSubmit = async (formData) => {
  if (formData?.id) {
    await request.put('/dish', formData)
    ElMessage.success('更新成功')
  } else {
    await request.post('/dish', formData)
    ElMessage.success('添加成功')
  }
  dialogRef.value.close()
  await handleQuery()
}

// 处理删除
const handleDelete = (row) => {
  confirm(`确定要删除该菜品吗？`, async () => {
    await request.delete(`/dish/${row.id}`)
    ElMessage.success('删除成功')
    await handleQuery()
  })
}

// 处理批量删除
const handleBatchDelete = (rows) => {
  confirm(`确定要删除选中的 ${rows.length} 个菜品吗？`, async () => {
    await Promise.all(rows.map(row => request.delete(`/dish/${row.id}`)))
    ElMessage.success('批量删除成功')
    await handleQuery()
  })
}
</script>

<style scoped>
</style>